<template>
  <div>
    <Header :left="true" leftText="返回" title="查看实验室检验不合格项" />
    <div>
      <DropdownMenu style="margin-top:10px;background-color:#D3D3D3">
        <DropdownItem v-model="siteIndex1" :options="sites1" @change="siteChange1" />
        <DropdownItem v-model="departIndex" :options="departments" @change="departChange" />
        <DropdownItem v-model="siteIndex" :options="sites" @change="siteChange" />
        <!-- <DropdownItem ref="time" title="时间" @open="showDialog = true" /> -->
      </DropdownMenu>
    </div>
    <!-- <van-dialog v-model="showDialog" title="查询条件选择" show-cancel-button confirm-button-text="确认" cancel-button-text="取消"
      @confirm="timeConfirm" @cancel="clearTime">
      <Form :style="autoHeight">
        <van-field readonly clickable name="timeStr" :value="valueStr" label="开始时间" placeholder="点击选择日期"
          @click="openStartTime" />
        <van-calendar v-model="showCalendarStr" @confirm="onConfirmStr" @closed="startConcel" :min-date="minDate"
          :max-date="maxDate" />
        <van-field readonly clickable name="timeEnd" :value="valueEnd" label="结束时间" placeholder="点击选择日期"
          @click="openEndTime" />
        <van-calendar v-model="showCalendarEnd" @confirm="onConfirmEnd" @closed="endConcel" :min-date="minDate"
          :max-date="maxDate" />
      </Form>
    </van-dialog> -->
    <!-- 统计图 -->
    <!-- 条形图 -->
    <!-- <div>
        <canvas id="mountNode" style="width:100%;height:250px;"></canvas>
      </div> -->
    <!-- <van-divider>表格统计</van-divider> -->
    <div>
      <v-table is-horizontal-resize style="width:100%;" :show-vertical-border="true" :columns="columns" :max-height="350"
        :table-data="tableData" row-hover-color="#eee" row-click-color="#edf7ff"></v-table>
    </div>
    <!-- <van-pagination width="this.screenWidth" class="pagination" force-ellipses v-model="queryParamsRead.pageNum"
      :total-items="queryParamsRead.total" @change="pgn_change_read" :items-per-page="queryParamsRead.pageSize" /> -->
  </div>
</template>
<script>
import {
  DropdownMenu,
  DropdownItem,
  Button,
  Cell,
  Field,
  Col,
  Row,
  Pagination,
  Sticky,
  Toast,
  Dialog,
  Divider,
  Calendar,
} from 'vant'
Vue.use(Divider)
Vue.use(Calendar)
Vue.use(Pagination)
Vue.use(Field)
Vue.use(Dialog)
import { _httpClient } from "@/libs/apisie";
import F2 from '@antv/f2/lib/index-all'
import Header from '@/components/header.vue'
import { VTable } from 'vue-easytable'
import 'vue-easytable/libs/themes-base/index.css'
import { storage } from '@/libs/utils'
import { removeToken, getToken, setBaseApiFrefix, getBaseApiFrefix } from '@/libs/auth'
export default {
  components: {
    Button,
    Header,
    Cell,
    Field,
    Col,
    Row,
    Sticky,
    DropdownMenu,
    DropdownItem,
    Divider,
    VTable,
    Dialog,
  },

  data() {
    return {
      id: "",
      //查询条件
      siteIndex: 0, //工厂
      siteIndex1: 0, //工厂
      departIndex: 0, //部门
      taskTypeIndex: 0, //任务类型
      valueStr: null, //开始时间查询条件
      valueEnd: null, //结束时间查询条件

      user: [],
      dpIndex: 0,
      //弹窗高度
      autoHeight: {
        height: '',
      },
      showCalendarStr: false,
      showCalendarEnd: false,
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2030, 11, 31),
      showDialog: false,
      queryParamsRead: {
        pageNum: 1,
        pageSize: 10,
        total: 0,
      },
      tableData: [
        // { BatchName: '质量部', SheetItemID: '30', ModeID: '20', RecordValue: '40', FieldCaption: '50' },
        // { BatchName: '工艺部', SheetItemID: '30', ModeID: '20', RecordValue: '40', FieldCaption: '50' },
        // { BatchName: '生产部', SheetItemID: '30', ModeID: '20', RecordValue: '40', FieldCaption: '50' },
      ],
      pointColumns: [
        //表格列头
        // {
        //   field: 'seqNum',
        //   title: '序号',
        //   width: 40,
        //   titleAlign: 'center',
        //   columnAlign: 'center',
        //   isResize: true,
        //   formatter: function (value, index) {
        //     return index + 1
        //   },
        //   titleCellClassName: 'title-cell-class-name-test',
        // },
        {
          field: 'BatchName',
          title: '检验批次名称',
          width: 120,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        // {
        //   field: 'SheetItemID',
        //   title: '检验批次代码',
        //   width: 120,
        //   titleAlign: 'center',
        //   columnAlign: 'center',
        //   isResize: true,
        //   titleCellClassName: 'title-cell-class-name-test',
        // },
        {
          field: 'FieldCaption',
          title: '检验项目',
          width: 200,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'ModeID',
          title: '模号',
          width: 110,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'RecordValue',
          title: '检验值',
          width: 75,
          titleAlign: 'center',
          columnAlign: 'center',
          isResize: true,
          titleCellClassName: 'title-cell-class-name-test',
        },
        {
          field: 'StandardValue',
          title: '标准值',
          width: 75,
          titleAlign: 'center',
          columnAlign: 'center',
          titleCellClassName: 'title-cell-class-name-test',
          isResize: true,
        }
        ,
        {
          field: 'StandardMaxValue',
          title: '标准值-上限',
          width: 150,
          titleAlign: 'center',
          columnAlign: 'center',
          titleCellClassName: 'title-cell-class-name-test',
          isResize: true,
        }
        ,
        {
          field: 'StandardMinValue',
          title: '标准值-下限',
          width: 150,
          titleAlign: 'center',
          columnAlign: 'center',
          titleCellClassName: 'title-cell-class-name-test',
          isResize: true,
        }
      ],

      columns: [],
      sites1: [], //工厂
      sites: [], //工厂
      departments: [], //部门
      taskTypes: [
        { value: 0, text: '点检' },
        { value: 1, text: '维修' },
      ], //任务类型
      data1: [], //饼图数据
      data: [],
    }
  },
  created: function () {
    let oldHight = api.winWidth
    this.screenWidth = oldHight
    //获取当前系统登录用户
    this.user = JSON.parse(storage.get('user'))
    //初始化设置弹窗高度
    this.autoHeight.height = '100px'
    //表格列头初始化
    this.columns = this.pointColumns
    this.id = api.pageParam.id;
    // alert(api.pageParam.CheckBatch);
    // alert(api.pageParam.CheckItem);
    this.siteIndex1 = "";
    this.departIndex = "";
    if (api.pageParam.CheckBatch != "" || api.pageParam.CheckBatch != null || api.pageParam.CheckBatch != undefined) {
      this.CheckBatch = api.pageParam.CheckBatch;
      this.siteIndex1 = api.pageParam.CheckBatch;
    }
    if (api.pageParam.CheckItem != "" || api.pageParam.CheckItem != null || api.pageParam.CheckItem != undefined) {
      this.CheckItem = api.pageParam.CheckItem;
      this.departIndex = api.pageParam.CheckItem.replace(/\s+/g, "");
    }
    //初始化查询条件
    //this.initQuertSiteList()
    this.init1(this.id);
    this.init2(this.id);
    this.init3(this.id);
    this.quertPointCheckTableListnew();
  },
  mounted: function () {
    //数据查询
    // this.queryPointCheckData()
  },

  methods: {
    //时间确认查询
    timeConfirm() {
      //重新查询数据
      this.queryPointCheckData()
    },
    pgn_change_read() {
      this.queryPointCheckData()
    },
    //查询点检任务数据
    queryPointCheckData() {
      // this.quertPointCheckList()
      this.quertPointCheckTableList()
    },
    siteChange1(value) {
      // this.siteIndex = value
      // this.initQuertDepartList(value)
      //重新查询数据
      this.quertPointCheckTableList()
    },
    //下拉框工厂数据切换
    siteChange(value) {
      // this.siteIndex = value
      // this.initQuertDepartList(value)
      //重新查询数据
      this.quertPointCheckTableList()
    },
    //部门数据切换
    departChange(value) {
      // this.departIndex = value
      //重新查询数据
      this.quertPointCheckTableList()
    },
    removeDuplicate(arr) {

      const newArr = []

      arr.forEach(item => {

        if (newArr.indexOf(item) === -1) {
          newArr.push(item)
        }
      })
      return newArr // 返回一个新数组
    },
    async init3() {
      let _this = this;
      try {
        let res = await _httpClient.get(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + this.id + '&ResultStatus=false')
        //alert(JSON.stringify(res));
        _this.sites1 = [];
        let site1 = { value: "全部", text: "全部" }
        _this.sites1.push(site1);
        res.Data.forEach(function (item, index) {
          // if (api.pageParam.CheckBatch != "" || api.pageParam.CheckBatch != null || api.pageParam.CheckBatch != undefined) {
          //   if (item.BatchName == api.pageParam.CheckBatch) {
          //     let site = { value: item.BatchName, text: item.BatchName }
          //     _this.sites1.push(site);
          //   }
          // }
          // else {
          let site = { value: item.BatchName, text: item.BatchName }
          _this.sites1.push(site);
          // }
        })
        _this.sites1 = Array.from(new Set(_this.sites1.map(JSON.stringify))).map(JSON.parse);
        _this.siteIndex1 = _this.sites1[0].value;
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },
    //获取检验批次
    async init1() {
      let _this = this;
      try {
        let res = await _httpClient.get(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + this.id + '&ResultStatus=false')
        //alert(JSON.stringify(res));
        _this.sites = [];
        let site1 = { value: "全部", text: "全部" }
        _this.sites.push(site1);
        res.Data.forEach(function (item, index) {
          let site = { value: item.ModeID, text: item.ModeID }
          _this.sites.push(site);
        })
        _this.sites = Array.from(new Set(_this.sites.map(JSON.stringify))).map(JSON.parse);
        _this.siteIndex = _this.sites[0].value;
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },
    unique(arr) {
      var newArr = [];
      for (var i = 0; i < arr.length; i++) {
        if (newArr.indexOf(arr[i]) === -1) {
          newArr.push(arr[i]);
        }
      }
      return newArr;
    },
    //获取检验项目
    async init2() {
      let _this = this;
      try {
        let res = await _httpClient.get(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + this.id + '&ResultStatus=false')
        //alert(JSON.stringify(res));
        _this.departments = [];
        let site1 = { value: "全部", text: "全部" }
        _this.departments.push(site1);
        res.Data.forEach(function (item, index) {
          // if (api.pageParam.CheckItem != "" || api.pageParam.CheckItem != null || api.pageParam.CheckItem != undefined) {
          //   let array1 = api.pageParam.CheckItem.split(";");
          //   array1.forEach(element => {
          //     if (element.replace(/\s+/g, "") == item.FieldCaption) {
          //       let site = { value: item.FieldCaption, text: item.FieldCaption }
          //       _this.departments.push(site);
          //     }
          //   });
          // }
          // else {
          let site = { value: item.FieldCaption, text: item.FieldCaption }
          _this.departments.push(site);
          // }
        })
        _this.departments = Array.from(new Set(_this.departments.map(JSON.stringify))).map(JSON.parse);
        _this.departIndex = _this.departments[0].value;
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },
    //初始化查询工厂下拉框
    async initQuertSiteList() {
      let _this = this
      try {
        let res = await _httpClient.post(_httpClient.getApiPrefix() + '/app/report/siteList')
        if (res.code === 200) {
          if (res.rows.length > 0) {
            _this.sites = []
            res.rows.forEach(function (item, index) {
              let site = { value: item.siteKey, text: item.siteName }
              _this.sites.push(site)
            })
            _this.siteIndex = _this.sites[0].value
            _this.initQuertDepartList()
            _this.queryPointCheckData()
          }
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },

    //初始化查询部门下拉框
    async initQuertDepartList() {
      let _this = this
      try {
        let res = await _httpClient.get(_httpClient.getApiPrefix() + '/FixedSheetBatch/GetList')
        if (res.code === 200) {
          alert(JSON.stringify(res));
          if (res.data.length > 0) {
            _this.departments = []
            // let depart = { value: 0, text: '所有部门' }
            // _this.departments.push(depart)
            for (let i = 0; i < res.data.length; i++) {
              let newDepart = { value: res.data[i].CheckBatchName, text: res.data[i].CheckBatchName }
              _this.departments.push(newDepart)
            }
            _this.departIndex = _this.departments[0].value
          }
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },

    //查询图表数据
    async quertPointCheckList() {
      let _this = this
      //部门
      let deptId = this.departIndex != 0 ? this.departIndex : null

      //工厂
      let site
      if (_this.sites.length != 0) {
        site = _this.siteIndex
      }
      let url = '/pc/report/repairCollect/chartList?siteKey=' + site
      if (deptId != null) {
        url += '&deptId=' + deptId
      }
      if (_this.valueStr != null) {
        url += '&startTime=' + _this.valueStr
      }
      if (_this.endTime != null) {
        url += '&endTime=' + _this.valueEnd
      }
      try {
        let res = await _httpClient.get(_httpClient.getApiPrefix() + url)
        if (res.code === 200) {
          _this.data = res.list
          if (res.list != null && res.list.length > 0) {
            _this.data = []
            for (let i = 0; i < res.list.length; i++) {
              let data1 = {
                deptName: res.list[i].deptName != null ? res.list[i].deptName : '无部门',
                taskType: '报修次数',
                taskNum: res.list[i].requestNum,
              }
              _this.data.push(data1)
              let data2 = {
                deptName: res.list[i].deptName != null ? res.list[i].deptName : '无部门',
                taskType: '响应次数',
                taskNum: res.list[i].responseNum,
              }
              _this.data.push(data2)
              let data3 = {
                deptName: res.list[i].deptName != null ? res.list[i].deptName : '无部门',
                taskType: '维修完成次数',
                taskNum: res.list[i].repairedNum,
              }
              _this.data.push(data3)
              let data4 = {
                deptName: res.list[i].deptName != null ? res.list[i].deptName : '无部门',
                taskType: '未完成次数',
                taskNum: res.list[i].noRepairedNum,
              }
              _this.data.push(data4)
            }
          }
          //调用方法绘制柱形图
          _this.drawChart()
        } else {
          alert(res.msg)
        }
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },
    async quertPointCheckTableListnew() {
      let _this = this;
      //var encodedUrl = encodeURI(_httpClient.getApiPrefix() + 'QualityCheckRecordItem/GetList?ParentId='+_this.id+'&ResultStatus=false');
      //alert(encodedUrl);
      try {
        // var encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '');
        var encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&FieldCaption=' + _this.departIndex.replace(/\+s/g,"") + '');
        //alert(encodedUrl);
        let res = await _httpClient.get(encodedUrl)
        // alert(encodedUrl);
        // alert(res.Data);
        _this.tableData = [];
        _this.tableData = res.Data;
      } catch (e) {
        alert(JSON.stringify(e))
      }
    },
    //查询表格数据
    async quertPointCheckTableList() {
      let _this = this;
      //BatchName
      // alert(_this.siteIndex1);
      if (_this.siteIndex1 == "全部") {
        _this.siteIndex1 = "";
      }
      if (_this.siteIndex == "全部") {
        _this.siteIndex = "";
      }
      if (_this.departIndex == "全部") {
        _this.departIndex = "";
      }
      // //ModeID
      // alert(_this.siteIndex);
      // //FieldCaption
      // alert(_this.departIndex);

      var encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&ModeID=' + _this.siteIndex + '&FieldCaption=' + _this.departIndex + '');



      // if (_this.siteIndex1 != "全部") {
      //   if (_this.siteIndex != "全部") {
      //     if (_this.departIndex != "全部") {
      //       encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&ModeID=' + _this.siteIndex + '&FieldCaption=' + _this.departIndex + '');
      //     }
      //     else {
      //       encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&ModeID=' + _this.siteIndex + '');
      //     }
      //   }
      //   else {
      //     encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&ModeID=' + _this.siteIndex + '&FieldCaption=' + _this.departIndex + '');
      //   }
      // }
      // else {
      //   if (_this.siteIndex != "全部") {
      //     if (_this.departIndex != "全部") {
      //       encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&ModeID=' + _this.siteIndex + '&FieldCaption=' + _this.departIndex + '');
      //     }
      //     else {
      //       encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&ModeID=' + _this.siteIndex + '&FieldCaption=' + _this.departIndex + '');
      //     }
      //   }
      //   else {
      //     encodedUrl = encodeURI(_httpClient.getApiPrefix() + '/QualityCheckRecordItem/GetList?ParentId=' + _this.id + '&ResultStatus=false&BatchName=' + _this.siteIndex1 + '&ModeID=' + _this.siteIndex + '&FieldCaption=' + _this.departIndex + '');
      //   }
      // }

      //alert(encodedUrl);
      try {
        let res = await _httpClient.get(encodedUrl)
        //alert(JSON.stringify(res));
        _this.tableData = [];
        _this.tableData = res.Data;
        // let index =0;
        // _this.tableData.forEach(element => {
        //     index = index + 1;
        //     if (element.BatchName =="") {
        //       delete _this.tableData[index];
        //     }
        // });
        if (_this.siteIndex1 == "") {
          _this.siteIndex1 = "全部";
        }
        if (_this.siteIndex == "") {
          _this.siteIndex = "全部";
        }
        if (_this.departIndex == "") {
          _this.departIndex = "全部";
        }
      } catch (e) {
        alert(JSON.stringify(e))
        if (_this.siteIndex1 == "") {
          _this.siteIndex1 = "全部";
        }
        if (_this.siteIndex == "") {
          _this.siteIndex = "全部";
        }
        if (_this.departIndex == "") {
          _this.departIndex = "全部";
        }
      }
    },

    //日期格式化
    formatDate(date) {
      let year = date.getFullYear()
      let mouth = date.getMonth() + 1
      if (mouth < 10) {
        mouth = '0' + mouth
      }
      let day = date.getDate()
      if (day < 10) {
        day = '0' + day
      }
      return year + '-' + mouth + '-' + day
    },

    //时间清空
    clearTime() {
      this.valueStr = ''
      this.valueEnd = ''
      //重新查询数据
      this.queryPointCheckData()
    },

    //开始时间取消
    startConcel() {
      // this.valueStr = ''
      this.autoHeight.height = '100px'
    },
    //结束时间取消
    endConcel() {
      // this.valueEnd = ''
      this.autoHeight.height = '100px'
    },

    //打开开始时间选择
    openStartTime() {
      this.showCalendarStr = true
      this.autoHeight.height = '400px'
    },

    //打开结束时间选择
    openEndTime() {
      this.showCalendarEnd = true
      this.autoHeight.height = '400px'
    },

    //开始时间确定
    onConfirmStr(date) {
      this.valueStr = this.formatDate(date)
      this.showCalendarStr = false
      this.autoHeight.height = '100px'
    },
    //结束时间确认
    onConfirmEnd(date) {
      this.valueEnd = this.formatDate(date)
      this.showCalendarEnd = false
      this.autoHeight.height = '100px'
    },
    //绘制柱状图
    drawChart() {
      var Shape = F2.Shape
      var Util = F2.Util
      Shape.registerShape('interval', 'text', {
        draw: function draw(cfg, container) {
          var points = this.parsePoints(cfg.points)
          var style = Util.mix(
            {
              fill: cfg.color,
              z: true, // 需要闭合
            },
            cfg.style
          )
          var intervalShape = container.addShape('rect', {
            attrs: Util.mix(
              {
                x: points[1].x,
                y: points[1].y,
                width: points[2].x - points[1].x,
                height: points[0].y - points[1].y,
              },
              style
            ),
          })

          var origin = cfg.origin._origin // 获取对应的原始数据记录
          var textShape = container.addShape('text', {
            zIndex: 1,
            attrs: {
              x: (points[1].x + points[2].x) / 2,
              y: points[1].y - 5, // 往上偏移 5 像素
              text: origin['taskNum'],
              fill: '#808080',
              textAlign: 'center',
              textBaseline: 'bottom',
              fontSize: 12, // 字体大小
            },
          })
          container.sort()
          return [intervalShape, textShape]
        },
      })

      var chart = new F2.Chart({
        id: 'mountNode',
        pixelRatio: window.devicePixelRatio,
      })
      chart.source(this.data)
      chart.legend(true)
      chart.legend({
        align: 'center',
        itemWidth: null, // 图例项按照实际宽度渲染
      })

      chart.tooltip({
        showItemMarker: false,
        onShow: function onShow(ev) {
          var item = ev.items
          // alert(JSON.stringify(item))
        },
      })

      chart
        .interval()
        .position('deptName*taskNum')
        // .color('taskType')
        .color('taskType', function (taskType) {
          if (taskType == '报修次数') {
            return '#F0A91D'
          } else if (taskType == '响应次数') {
            return '#3BA4F5'
          } else if (taskType == '维修完成次数') {
            return '#1BCAB9'
          } else if (taskType == '未完成次数') {
            return '#B968E9'
          } else {
            return '#7f8da9'
          }
        })
        .shape('text')
        .adjust({
          type: 'dodge',
          marginRatio: 0.2,
        })
        .style({
          radius: [0, 0, 0, 0],
        })

      chart.render()
    },
  },
}
</script>
<style>
body {
  background-color: White;
}

.selectdTextScroll {
  display: inline-block;
  /* position: fixed; */
  top: 9rem;
  overflow: scroll;
  right: 0;
  width: 100%;
  height: 300px;
  z-index: 1;
}

.title-cell-class-name-test {
  background-color: #f8f8f8;
  color: #000000;
}
</style>
  